import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  xls: 'application/vnd.ms-excel',
  zip: 'application/zip',
  pdf: 'application/pdf',
  mp3: 'audio/*',
  mp4: 'video/*',
  img: 'image/*',
}

const baseUrl = (process.env.NODE_ENV === 'production' ? location.origin : '') +  process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
  var url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() },
  }).then(res => {
    resolveBlob(res, mimeMap.zip)
  })
}
/**
 * 下载文件，get
 * @param {String} str blob响应内容
 * @param {String} mimeType mimeMap的key
 */
export function downLoadFile(str, mimeType, params = null, method='get', callback) {
  var url = baseUrl + str
  axios({
    method: method,
    url: url,
    params,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(res => {
    resolveBlob(res, mimeMap[mimeType], callback)
  }).catch(err => {
    Message({
      message: err,
      type: 'error'
    })
  })
}
/**
 * 下载文件，post
 * @param {String} str blob响应内容
 * @param {String} mimeType mimeMap的key
 */
 export function downLoadFileReqBody(str, mimeType, fileUrl, callback) {
  var url = baseUrl + str
  axios({
    method: 'post',
    url: url,
    data: fileUrl,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(res => {
    return resolveBlob(res, mimeMap[mimeType], callback)
  })
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType, callback) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  if (contentDisposition) {
    var result = patt.exec(contentDisposition)
    var fileName = result[1]
    fileName = fileName.replace(/\"/g, '')
    var objectUrl = URL.createObjectURL(blob)
    aLink.href = objectUrl
    aLink.setAttribute('download', fileName) // 设置下载文件名称
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink)
    if (callback) callback();
  } else {
    Message({
      message: '下载接口异常，缺少contentDisposition',
      type: 'error'
    })
  }
}
